package org.jeecg.modules.demo.baseorde.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basemembervipcoupon.entity.BaseMemberVipCoupon;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseorde.entity.BaseOrder;
import org.jeecg.modules.demo.baseorde.entity.BaseOrderCommodityJson;
import org.jeecg.modules.demo.baseorde.entity.BaseOrderInfo;
import org.jeecg.modules.demo.baseorde.service.IBaseOrderService;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 订单
 * @Author: jeecg-boot
 * @Date: 2022-01-27
 * @Version: V1.0
 */
@Api(tags = "订单")
@RestController
@RequestMapping("/baseorde/baseOrder")
@Slf4j
public class BaseOrderController extends JeecgController<BaseOrder, IBaseOrderService> {
    @Autowired
    private IBaseOrderService baseOrderService;
    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;
    @Autowired
    private RedisUtils redisUtils;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     *
     * @param baseOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单-分页列表查询")
    @ApiOperation(value = "订单-分页列表查询", notes = "订单-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(BaseOrder baseOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        QueryWrapper<BaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, baseOrder, req.getParameterMap());
        Page<BaseOrder> page = new Page<BaseOrder>(pageNo, pageSize);
        IPage<BaseOrder> pageList = baseOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询订单列表
     *
     * @param stockName
     * @param memberName
     * @param orderCode
     * @param beginTime
     * @param endTime
     * @param name
     * @param patternPayment
     * @param orderType
     * @param orderStatus
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "查询订单列表")
    @ApiOperation(value = "查询订单列表", notes = "查询订单列表")
    @GetMapping(value = "/searchOrderList")
    public Result<?> searchOrderList(@RequestParam(name = "stockName", defaultValue = "") String stockName,
                                     @RequestParam(name = "memberName", defaultValue = "") String memberName,
                                     @RequestParam(name = "orderCode", defaultValue = "") String orderCode,
                                     @RequestParam(name = "beginTime", defaultValue = "") String beginTime,
                                     @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                     @RequestParam(name = "name", defaultValue = "") String name,
                                     @RequestParam(name = "patternPayment", defaultValue = "") String patternPayment,
                                     @RequestParam(name = "orderType", defaultValue = "") String orderType,
                                     @RequestParam(name = "orderStatus", defaultValue = "") String orderStatus,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                     HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        Page<BaseOrder> page = new Page<BaseOrder>(pageNo, pageSize);
        IPage<BaseOrder> pageList = baseOrderService.searchOrderList(page, stockName, memberName, orderCode, beginTime,
                endTime, name, patternPayment, orderType, orderStatus, storeId);
        return Result.OK(pageList);
    }

    /**
     * 查询线上自提订单
     * <p>
     * 600
     * 股本余额（可使用余额 1092）
     * <p>
     * 是否使用 会员余额和股本余额进行折扣
     * 会员余额___200__  325   balanceAmount
     * 股本余额__100__  320  stockBalanceAmount
     * <p>
     * 折扣后需要微信支付 0元  realAmount
     * <p>
     * 支付类型  微信支付 03
     * 支付金额 300
     *
     * @param pageNo
     * @param storeId
     * @param memberId
     * @param orderStatus
     * @return
     */
    @AutoLog(value = "根据会员id获取订单列表")
    @ApiOperation(value = "根据会员id获取订单列表", notes = "根据会员id获取订单列表")
    @GetMapping(value = "/getOrderInfoListByMemberId")
    public Result<List<BaseOrderInfo>> getOrderInfoListByMemberId(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "storeId", defaultValue = "") String storeId,
                                                                  @RequestParam(name = "memberId", defaultValue = "") String memberId,
                                                                  @RequestParam(name = "orderStatus", defaultValue = "") String orderStatus) {
        Result<List<BaseOrderInfo>> result = new Result<>();
        List<BaseOrderInfo> list = baseOrderService.getOrderInfoListByMemberId(pageNo, 10, storeId, memberId, orderStatus);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 更新订单的商品明细表
     *
     * @return
     */
    @AutoLog(value = "订单-更新订单的商品明细表")
    @ApiOperation(value = "订单-更新订单的商品明细表", notes = "订单-更新订单的商品明细表")
    @GetMapping(value = "/updateCommodityJson")
    public Result<?> updateCommodityJson() {
        List<BaseOrder> listOrder = baseOrderService.list();
        if (listOrder != null) {
            for (int i = 0; i < listOrder.size(); i++) {
                BaseOrder baseOrder = listOrder.get(i);
                String strCommodity = baseOrder.getCommodityListJsonStr();
                JSONArray objects = JSONObject.parseArray(strCommodity);
                List<Map<String, Object>> auditListMap = (List<Map<String, Object>>) ToolsUtils.translate(objects);
                if (auditListMap != null) {
                    for (int j = 0; j < auditListMap.size(); j++) {
                        String staffId = "";
                        if (auditListMap.get(j).get("staffId") != null) {
                            staffId = auditListMap.get(j).get("staffId").toString();
                        }
                        if (staffId != "") {
                            BaseOrderCommodityJson commdoityJson = new BaseOrderCommodityJson();
                            commdoityJson.setId(UUID.randomUUID().toString());
                            commdoityJson.setOrderCode(baseOrder.getOrderCode());
                            commdoityJson.setName(auditListMap.get(j).get("name").toString());
                            commdoityJson.setSpecification(auditListMap.get(j).get("specification").toString());
                            commdoityJson.setCount(Integer.parseInt(auditListMap.get(j).get("count").toString()));
                            commdoityJson.setPrice(Double.parseDouble(auditListMap.get(j).get("price").toString()));
                            commdoityJson.setTotalPrice(Double.parseDouble(auditListMap.get(j).get("totalPrice").toString()));
                            commdoityJson.setDiscountAmount(Double.parseDouble(auditListMap.get(j).get("discountAmount").toString()));
                            commdoityJson.setFree(false);
                            commdoityJson.setStaffPercentage(auditListMap.get(j).get("staffPercentage").toString());
                            commdoityJson.setStaffId(auditListMap.get(j).get("staffId").toString());
                            //commdoityJson.setStaffName(auditListMap.get(j).get("staffName").toString());
                            commdoityJson.setType(Integer.parseInt(auditListMap.get(j).get("type").toString()));
                            try {
                                commdoityJson.setStaffCommission(Double.parseDouble(auditListMap.get(j).get("staffCommission").toString()));
                            } catch (Exception ex) {
                                commdoityJson.setStaffCommission(0.0);
                            }

                            baseOrderService.addCommodityJson(commdoityJson);
                        }
                    }
                }
            }
        }
        return Result.OK();
    }

    /**
     * 添加
     *
     * @param baseOrder
     * @return
     */
    @AutoLog(value = "订单-添加")
    @ApiOperation(value = "订单-添加", notes = "订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody BaseOrder baseOrder) {
        String strCommodity = baseOrder.getCommodityListJsonStr();
        JSONArray objects = JSONObject.parseArray(strCommodity);
        List<Map<String, Object>> auditListMap = (List<Map<String, Object>>) ToolsUtils.translate(objects);
        if (auditListMap != null) {
            for (int j = 0; j < auditListMap.size(); j++) {
                String staffId = "";
                if (auditListMap.get(j).get("staffId") != null) {
                    staffId = auditListMap.get(j).get("staffId").toString();
                }
                if (staffId != "") {
                    BaseOrderCommodityJson commdoityJson = new BaseOrderCommodityJson();
                    commdoityJson.setId(UUID.randomUUID().toString());
                    commdoityJson.setOrderCode(baseOrder.getOrderCode());
                    commdoityJson.setName(auditListMap.get(j).get("name").toString());
                    commdoityJson.setSpecification(auditListMap.get(j).get("specification").toString());
                    commdoityJson.setCount(Integer.parseInt(auditListMap.get(j).get("count").toString()));
                    commdoityJson.setPrice(Double.parseDouble(auditListMap.get(j).get("price").toString()));
                    commdoityJson.setTotalPrice(Double.parseDouble(auditListMap.get(j).get("totalPrice").toString()));
                    commdoityJson.setDiscountAmount(Double.parseDouble(auditListMap.get(j).get("discountAmount").toString()));
                    commdoityJson.setFree(false);
                    commdoityJson.setStaffPercentage(auditListMap.get(j).get("staffPercentage").toString());
                    commdoityJson.setStaffId(auditListMap.get(j).get("staffId").toString());
                    //commdoityJson.setStaffName(auditListMap.get(j).get("staffName").toString());
                    commdoityJson.setType(Integer.parseInt(auditListMap.get(j).get("type").toString()));
                    try {
                        commdoityJson.setStaffCommission(Double.parseDouble(auditListMap.get(j).get("staffCommission").toString()));
                    } catch (Exception ex) {
                        commdoityJson.setStaffCommission(0.0);
                    }

                    baseOrderService.addCommodityJson(commdoityJson);
                }
            }
        }

        baseOrderService.save(baseOrder);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param baseOrder
     * @return
     */
    @AutoLog(value = "订单-编辑")
    @ApiOperation(value = "订单-编辑", notes = "订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody BaseOrder baseOrder) {
        baseOrderService.updateById(baseOrder);
        return Result.OK("编辑成功!");
    }

    /**
     * 在线订单自提
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "在线订单自提")
    @ApiOperation(value = "在线订单自提", notes = "在线订单自提")
    @DeleteMapping(value = "/selfMention")
    public Result<?> selfMention(@RequestParam(name = "orderId", required = true) String orderId) {
        baseOrderService.selfMention(orderId);
        return Result.OK("自提成功!");
    }

    /**
     * 在线订单退款
     *
     * @param orderId
     * @return
     */
    @AutoLog(value = "在线订单退款")
    @ApiOperation(value = "在线订单退款", notes = "在线订单退款")
    @DeleteMapping(value = "/refund")
    public Result<?> refund(@RequestParam(name = "orderId", required = true) String orderId) {
        baseOrderService.refund(orderId);
        return Result.OK("退款成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-通过id删除")
    @ApiOperation(value = "订单-通过id删除", notes = "订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        baseOrderService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "订单-批量删除")
    @ApiOperation(value = "订单-批量删除", notes = "订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.baseOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "订单-通过id查询")
    @ApiOperation(value = "订单-通过id查询", notes = "订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        BaseOrder baseOrder = baseOrderService.getById(id);
        if (baseOrder == null) {
            return Result.error("未找到对应数据");
        }
        Map<String, Object> map = ToolsUtils.objectToMap(baseOrder);
        map.put("couponListJson", JSON.parse(baseOrder.getCouponListJsonStr()));
        map.put("commodityListJson", JSON.parse(baseOrder.getCommodityListJsonStr()));
        try{
            JSONArray objects = JSON.parseArray(baseOrder.getCommodityListJsonStr());
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = (JSONObject)objects.get(i);
                Integer count = jsonObject.getInteger("count");
                Double totalPrice = jsonObject.getDouble("totalPrice");
                List<String> saleName=new ArrayList<>();
                List<String> ticheng = new ArrayList<>();
                List<String> juse = new ArrayList<>();
                JSONArray staffs = jsonObject.getJSONArray("staffs");
                for (int j = 0; j < staffs.size(); j++) {
                    JSONObject staff = (JSONObject) staffs.get(j);

                    String workActor = staff.getString("workActor");
                    if ("1".equals(workActor)) {
                        saleName.add(staff.getString("staffName"));
                        juse.add("销售");
                        if ("1".equals(staff.getString("shareWay"))) {
                            Double value = staff.getDouble("value");
                            BigDecimal tc = BigDecimal.valueOf(totalPrice).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(100));
                            ticheng.add(String.valueOf(ToolsUtils.formatNumber(tc)));
                        }
                        if ("2".equals(staff.getString("shareWay"))) {
                            Double value = staff.getDouble("value");
                            ticheng.add(String.valueOf(count * value));
                        }
                    } else if ("2".equals(workActor)) {
                        saleName.add(staff.getString("staffName"));
                        juse.add("技师");
                        if ("1".equals(staff.getString("shareWay"))) {
                            Double value = staff.getDouble("value");
                            BigDecimal tc = BigDecimal.valueOf(totalPrice).multiply(BigDecimal.valueOf(value)).divide(BigDecimal.valueOf(100));
                            ticheng.add(String.valueOf(ToolsUtils.formatNumber(tc)));
                        }
                        if ("2".equals(staff.getString("shareWay"))) {
                            Double value = staff.getDouble("value");
                            ticheng.add(String.valueOf(count * value));
                        }
                    }

                }
                jsonObject.put("saleName",saleName);
                jsonObject.put("ticheng", ticheng);
                jsonObject.put("juese", juse);
            }
            map.put("commodityListJson", JSONObject.toJSON(objects));

        }catch(Exception e){

        }


        return Result.OK(map);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param baseOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaseOrder baseOrder) {
        //return super.exportXls(request, baseOrder, BaseOrder.class, "订单");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<BaseOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, baseOrder, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<BaseOrder> pageList = baseOrderService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "订单"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, BaseOrder.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("订单数据", "导出人:" + user.getRealname(), "订单");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BaseOrder.class);
    }

    /**
     * 获取订单已使用优惠劵
     */
    @AutoLog(value = "订单-获取订单已使用优惠劵")
    @ApiOperation(value = "订单-获取订单已使用优惠劵", notes = "订单-获取订单已使用优惠劵")
    @GetMapping(value = "/getReceiveCoupon")
    public Result<?> getReceiveCoupon(String vipIds,
                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<BaseMemberVipCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", Arrays.asList(vipIds.split(",")));
        Page<BaseMemberVipCoupon> page = new Page<>(pageNo, pageSize);
        IPage<BaseMemberVipCoupon> pageList = baseMemberVipCouponService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

}
